package site.anxuan.seckill.controller;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnel;
import com.google.common.hash.Funnels;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import site.anxuan.seckill.common.Results;
import site.anxuan.seckill.entity.Item;
import site.anxuan.seckill.entity.Result;
import site.anxuan.seckill.service.ItemService;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/item")
@AllArgsConstructor
public class ItemController implements InitializingBean {

    private final ItemService itemService;

    private final BloomFilter<Integer> bloomFilter =
            BloomFilter.create(Funnels.integerFunnel(), 1000, 0.00001);

    @GetMapping("/list")
    public Result<List<Item>> getList() {
        return Results.success(itemService.getListOnPromotion());
    }

    @GetMapping("/detail/{itemId}")
    public Result<Item> getById(@PathVariable Integer itemId) {
        if (bloomFilter.mightContain(itemId)) {
            return Results.failure();
        }
        Item item = itemService.getByIdFromCache(itemId);
        if (item == null) {
            synchronized (ItemController.class) {
                item = itemService.getByIdFromCache(itemId);
                if (item == null) {
                    item = itemService.getById(itemId);
                }
            }
        }
        return Results.success(item);
    }

    @Override
    public void afterPropertiesSet() {
        itemService.getListOnPromotion()
                .stream().map(Item::getId)
                .forEach(bloomFilter::put);
    }

}
